﻿using Dingding.Helper.Redis;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

using System.Data;
using System.Linq;
//using Newtonsoft.Json;
using System.Reflection;
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
//在ASP.NET Core中，System.Text.Json是默认的JSON序列化器，可以方便地通过配置选项进行定制。

//如果需要使用Newtonsoft.Json，需要额外安装Microsoft.AspNetCore.Mvc.NewtonsoftJson包，并在Startup中配置。



using System.Text.Json;
using static WebApplication1.Controllers.Pono_NoController;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class Pono_NoController : ControllerBase
    {




        string ps_name = "PostPono_No_GetV1";


        /// <summary>
        /// 原始数据；[炉号钩号]
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("login")]
        [AllowAnonymous]

        public ActionResult Login([FromBody] LoginModel req)
        {



            using (var redisHelper = new StackExchange_RedisV2())
            {
                // 写入单条记录（同步）
                bool keySuccess = redisHelper.SetValue("key1v2", "value1", TimeSpan.FromSeconds(30));
                 

                // 设置缓存
                var user = new User { Id = 1, Name = "John Doe soft sight", Email = "john@example.com" };



                var serializedValue = JsonSerializer.Serialize(user);


                bool setSuccess = redisHelper.SetValue("user:1", serializedValue, TimeSpan.FromHours(1));

                // bool setSuccess = _cacheManager.Set("user:1", user, TimeSpan.FromHours(1));


                Console.WriteLine($"设置缓存是否成功: {setSuccess}");

                //DataTable table_mat_nos = JsonConvert.DeserializeObject<DataTable>(mat_nos);
                // 获取缓存
                var cachedUser = JsonSerializer.Deserialize<User>(redisHelper.GetValue("user:1"));

               

                if (cachedUser != null)
                {
                    Console.WriteLine($"获取到缓存用户: {cachedUser.Name}");
                }

                

                //// 读取单条记录（同步）
                //var value1 = redisHelper.GetValue("key1");
                //Console.WriteLine($"Key1: {value1}");




                // 写入多条记录（异步）
                var multipleValues = new Dictionary<string, string>
                {
                    { "key3V", "aasdfasdf" },
                    { "key4V2", "adfasdfasdf" }
                };
                redisHelper.SetValues(multipleValues, TimeSpan.FromMinutes(20));





                // 读取多条记录（异步）
                var keysToRead = new List<string> { "key3V", "key4V2" };
                var results = redisHelper.GetValues(keysToRead);

                foreach (var kvp in results)
                {
                    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
                }



            }














            Console.WriteLine("["+req.username + "]");

            var sessionId = Guid.NewGuid().ToString("N");
            var now = DateTime.UtcNow;


            var minutesStr = "30";//System.Configuration.ConfigurationManager.AppSettings["Auth:SessionTimeoutMinutes"];
            if (!int.TryParse(minutesStr, out var minutes)) minutes = 30;
            var ttl = TimeSpan.FromMinutes(minutes);

            // 存 Redis
            // RedisConnectionManager.SessionStore.StoreSession(session, ttl);


 


            // 1. 设置简单的 Cookie
            Response.Cookies.Append("AuthSession", sessionId, new CookieOptions
            {
                HttpOnly = true, // 防止 XSS 攻击
                Secure = false,   // true为仅通过 HTTPS 传输
                SameSite = SameSiteMode.Strict, // CSRF 保护
                Expires = DateTime.UtcNow.AddHours(1), // 过期时间
                Path = "/" // 有效路径
            });



            // 2. 设置包含用户信息的 Cookie
            var userInfo = new { Username ="wangbiao", Role = "Admin", LoginTime = DateTime.UtcNow };
            //var userInfoJson = JsonConvert.SerializeObject(userInfo);
            var userInfoJson = JsonSerializer.Serialize(userInfo);


            

            Response.Cookies.Append("UserInfo", userInfoJson, new CookieOptions
            {
                HttpOnly = true,
                Secure = true,
                SameSite = SameSiteMode.Lax,
                Expires = DateTime.UtcNow.AddHours(2),
                Path = "/api"
            });


            return Ok(new ApiResponse { Success = true, Message = "登录成功" + sessionId.ToString() });

        }




        /// <summary>
        /// 原始数据；[炉号钩号]
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("inq")]
        [AllowAnonymous]

        public ActionResult inq([FromBody] LoginModel req)
        {
            var result = new List<dynamic>();
            try
            {

           
            string appid = "LTCE";
            string staff_id = "oTHJ_wu0mFAdMSniwygWWO3164uI";
           

            Console.WriteLine("[" + req.username + "]");

            var sessionId = Guid.NewGuid().ToString("N");
            var now = DateTime.UtcNow;

            //获取该用户所有可能的权限列表；支持1个人员配置多个：权限组；

            string str_temp = "  select TA.EXTEND_2 from    "
                           + "  tpabma22 TA, tqmcca01 TB    "
                           + "   where TA.func_name =  '" + appid + "' "
                           + "   AND TB.WEIXIN_NO = '" + staff_id + "' "
                           + "   AND TB.FORM_NAME_ROLE LIKE '%' || TA.ROLE || '%' "
                   ;


                str_temp = "select count(*) from  TSMPE11 ";

            EI.EIInfo outBlock_temp = EF.Utility.ExecQuery(str_temp);
           

            string str_form_name = "";
            for (int i = 0; i < outBlock_temp.Tables[0].Rows.Count; i++)
            {
                str_form_name = str_form_name + outBlock_temp.Tables[0].Rows[i][0].ToString() + ",";
            }


            string str1 = " select distinct class_code,class_desc,type_no  from  tpabma21 "
                        + " where   func_name = '" + appid + "'  "
                        + " and  '" + str_form_name + "' LIKE '%' ||FORM_NO || '%' "
                        + " order by  type_no"
                        ;


            string str2 = "   select * from  tpabma21     "
                        + "   where   func_name = '" + appid + "'  "
                        + "   and  '" + str_form_name + "' LIKE '%' || FORM_NO || '%' "
                        + "   order by  type_no,seq_now   "
                        ;



            EI.EIInfo outBlock = EF.Utility.ExecQuery(str1);
            EI.EIInfo outBlock2 = EF.Utility.ExecQuery(str2);

            DataTable dtTemp = null;
            string class_code = string.Empty;


           

            for (int i = 0; i < outBlock.Tables[0].Rows.Count; i++)
            {
                var classObj = new
                {
                    class_desc = outBlock.Tables[0].Rows[i]["CLASS_DESC"].ToString(),
                    items = new List<dynamic>()
                };

                class_code = outBlock.Tables[0].Rows[i]["CLASS_CODE"].ToString();

                if (outBlock2.Tables[0].Select("CLASS_CODE  = '" + class_code + "'").Count<DataRow>() >= 1)
                {
                    dtTemp = outBlock2.Tables[0].Select("CLASS_CODE  = '" + class_code + "'").CopyToDataTable<DataRow>();

                    //子项明细；
                    for (int j = 0; j < dtTemp.Rows.Count; j++)
                    {
                        classObj.items.Add(new
                        {
                            link_address = dtTemp.Rows[j]["LINK_ADDRESS"].ToString(),
                            menu_icon = dtTemp.Rows[j]["MENU_ICON"].ToString(),
                            form_name = dtTemp.Rows[j]["FORM_NAME"].ToString(),
                        });
                    }
                }

                result.Add(classObj);

            }

            //context.Response.Write(JsonConvert.SerializeObject(result));
            //return Ok(new ApiResponse { Success = true, Message = "登录成功" + sessionId.ToString() });

            //JsonSerializer.Serialize(result);

            //return Ok(result);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

            }

            return Ok(result);

        }







        public class ApiResponse
        {
            public bool Success { get; set; }
            public string Message { get; set; }
        }



        public class UserInfo
        {
            public string Username { get; set; } = string.Empty;
            public string Role { get; set; } = string.Empty;
            public DateTime LoginTime { get; set; }
        }

       

        public class User
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
        }

    }
}
